package com.ydj.framework.module.city.init;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.ydj.framework.module.init.BaseInit;
import com.ydj.framework.module.city.entity.dao.DictCityDao;
import com.ydj.framework.module.city.entity.DictCity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
//@Component
public class DictCityListInit extends BaseInit {
    @Getter
    @Setter
    @AllArgsConstructor
    public static class CityItem {
        private Long id;
        private Integer level;
        private String name;
        private Long parentId;
    }

    @Override
    protected InitContext getContext() {
        return new InitContext("框架-初始化城市列表", 5);
    }

    @Override
    protected void doAction() throws IOException {
        initCityList();
    }

    @Autowired
    private DictCityDao dictCityDao;

    private void initCityList() throws IOException {
        String path = "/dict/DictCity.json";
        log.info("开始加载城市List开始({})", path);
        Resource resource = new ClassPathResource(path);
        String data;
        try (InputStream inputStream = resource.getInputStream()) {
            data = IoUtil.read(inputStream, StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("加载城市List失败", e);
            throw e;
        }

        // 整表清空
        dictCityDao.remove(new QueryWrapper<>());

        final int saveOnceCount = 500;

        String[] lines = data.split("\n");
        List<DictCity> toBeSaveList = new ArrayList<>(lines.length);
        int saveToDbCount = 0;
        for (String line : lines) {
            CityItem jsonItem = new Gson().fromJson(line, CityItem.class);
            DictCity dictCity = new DictCity();
            dictCity.setName(jsonItem.getName())
                    .setLevel(jsonItem.getLevel())
                    .setParentId(jsonItem.getParentId())
                    .setId(jsonItem.getId());
            toBeSaveList.add(dictCity);
            if (toBeSaveList.size() >= saveOnceCount) {
                saveToDbCount += saveOnceCount;
                log.info("城市数据，写入数据库({}/{})", saveToDbCount, lines.length);
                dictCityDao.saveOrUpdateBatch(toBeSaveList);
                toBeSaveList.clear();
            }
        }
        if (!toBeSaveList.isEmpty()) {
            saveToDbCount += toBeSaveList.size();
            log.info("城市数据，写入数据库({}/{})", saveToDbCount, lines.length);
            dictCityDao.saveOrUpdateBatch(toBeSaveList);
        }
    }
}